<?php


namespace App\Http\Controllers\admin\service;


use App\Http\Controllers\admin\model\AdminModel;
use App\Http\Controllers\admin\model\AdminSnModel;
use App\Http\Controllers\admin\model\AppInstallModel;
use App\Http\Controllers\admin\model\BatchModel;
use App\Http\Controllers\admin\model\ParentAppModel;
use App\Http\Controllers\admin\model\ParentSnModel;
use App\Http\Controllers\admin\model\ScreenshotModel;
use App\Http\Controllers\admin\model\SendTeacherModel;
use App\Http\Controllers\admin\model\TeacherAppModel;
use App\Http\Controllers\admin\model\TeacherSnModel;
use App\Http\Controllers\admin\model\TimeControlModel;
use App\Http\Controllers\utils\LogUtil;
use App\Http\Controllers\utils\ToolUtil;
use Illuminate\Support\Facades\DB;

class SnService
{



    /**
     * 编辑老师sn
     * @param $param
     * @return false|string
     */
    public static function editTeacherSn($param){

        $id = (int)$param['id'];
        $uid = (int)$param['userId'];
        $batch_id = (int)$param['batch_id'];

        $admin = AdminModel::queryFirst(['id'=>$uid],['group_id']);
        if($admin['group_id'] !== 3){
            return ToolUtil::returnJson(300,'不是老师组别');
        }

        $TeacherSn = TeacherSnModel::queryFirst(['t.admin_sn_id'=>$id,'t.admin_id'=>$uid],['a.value','t.batch_id']);
        $batch = DB::table('t_batch')->where(['id'=>$batch_id,'admin_id'=>$uid])->first(['id']);

        if(empty($TeacherSn)){
            return ToolUtil::returnJson(300,'sn错误');
        }
        if(empty($batch)){
            return ToolUtil::returnJson(300,'班级错误');
        }
        if($TeacherSn['batch_id'] == $batch_id){
            return ToolUtil::returnJson(300,'请修改班级再提交');
        }

        $res = TeacherSnModel::edit(['admin_sn_id'=>$id],['batch_id'=>$batch_id]);

        $param['remark'] = 'Teacher编辑SN';
        if($res){

            $param['batch'] = array($TeacherSn['value']);
            $param['status'] = 1;
            $param['contentType'] = 17;
            $param['type'] = 2;
            $param['statusType'] = '修改班级';
            $param['title'] = 'OK';
            $param['details'] = ToolUtil::handleSuccessOrError(['sn'=>$TeacherSn['value']]);
            LogUtil::addAdminLog($param);
            $jPush = LogUtil::addPushLog($param);
            if(in_array(200,$jPush)){
                return ToolUtil::returnJson(200,'成功');
            }
            return ToolUtil::returnJson(200,'成功.');

        }else{
            $param['details'] = ToolUtil::handleSuccessOrError(['sn'=>$TeacherSn['value']],0);
            LogUtil::addAdminLog($param);
            return ToolUtil::returnJson(300,'失败');
        }

    }

    /**
     * 编号获取班级列表
     * @param $param
     * @return false|string
     */
    public static function queryIdBatchList($param){
        $data = BatchModel::queryWhere(['admin_id'=>$param['userId']],['id','name']);
        if(count($data)){
            return ToolUtil::returnJson(200,'成功',$data);
        }
        return ToolUtil::returnJson(400,'没有数据');
    }

    //学员维护
    public static function importSnBatch($param){

        try {
            if(empty($param['userId'])){
                return ToolUtil::returnJson(300,'用户编号错误');
            }
            $uid = (int)$param['userId'];
            $batch_id = (int)$param['batch_id'];
            if(empty($batch_id)){
                return ToolUtil::returnJson(300,'班级不能为空');
            }

            $batch = BatchModel::queryFirst(['id'=>$batch_id,'admin_id'=>$uid],['id']);
            if(empty($batch)){
                return ToolUtil::returnJson(300,'班级错误');
            }

            $admin = AdminModel::queryFirst(['id'=>$uid],['group_id']);
            if(empty($admin)){
                return ToolUtil::returnJson(301,'用户不存在');
            }

            if($admin['group_id'] !== 3){
                return ToolUtil::returnJson(303,'不是老师组别');
            }

            if(!ToolUtil::checkExcelSuffix($param)){
                return ToolUtil::returnJson(302,'文件类型必须为xlsx或xls');
            }
            $phpReader = new \PHPExcel_Reader_Excel2007();
            $phpExcel = $phpReader->load($param['file']);
            $currentSheet = $phpExcel->getSheet(0);//获取第一个表单
            $allRow = $currentSheet->getHighestRow();//获取总行数
            $maxColumn = $currentSheet->getHighestColumn();//获取最大列号
            $allColumn=\PHPExcel_Cell::columnIndexFromString($maxColumn);//获取总列数
            $snLenArr = [];//记录不等于12位的sn码行数
            $success = 0;//记录成功数
            $errorAll = [];//记录失败行数
            $adminAll = [];//管理员sn失败行数
            $teacherAll = [];//管理员sn失败行数
            $createTime = time();
            $param['remark'] = '学员维护导入sn码';
            DB::beginTransaction();
            set_time_limit(0);
            for ($currentRow=2;$currentRow<=$allRow;$currentRow++){
                for ($currentColumn=0;$currentColumn<$allColumn;$currentColumn++){
                    $val = trim($currentSheet->getCellByColumnAndRow($currentColumn,$currentRow)->getValue());
                    if(strlen($val)!==12){
                        $snLenArr[$currentRow] = $currentRow;
                        break;
                    }
                    $value = AdminSnModel::valueGetId(['value'=>$val]);
                    if(empty($value)){
                        $adminAll[$currentRow] = $currentRow;
                        break;
                    }

                    $res = DB::table('t_teacher_sn')->where(['admin_sn_id'=>$value,'admin_id'=>$uid])->first(['id']);

                    if(empty($res)){
                        $teacherAll[$currentRow] = $currentRow;
                        break;
                    }
                    $update = DB::table('t_teacher_sn')->where(['admin_sn_id'=>$value,'admin_id'=>$uid])->update(['batch_id'=>$batch_id]);
                    if($update){
                        $success++;
                        $param['details'] = ToolUtil::handleSuccessOrError(['sn'=>$val]);
                        LogUtil::addAdminLog($param);
                        break;                            
                    }else{
                        $errorAll[$currentRow] = $currentRow;
                        break;                        
                    }

                }
            }
            DB::commit();
            $result['success'] = $success;
            $result['total'] = $allRow-1;
            $result['snLen'] = array_values($snLenArr);
            $result['errorRow'] = array_values($errorAll);
            $result['snErrorRow'] = array_values($adminAll);
            $result['teacherErrorRow'] = array_values($teacherAll);

            return ToolUtil::returnJson(200,'成功',$result);
        }catch (\Exception $exception){
            return ToolUtil::returnJson(500,$exception->getMessage());
        }
    }


    /**
     * 导入sn信息
     * @param $param
     * @return false|string
     * @throws \PHPExcel_Exception
     * @throws \PHPExcel_Reader_Exception
     */
    public static function importSn($param){
        try {
            if(empty($param['userId'])){
                return ToolUtil::returnJson(300,'用户编号错误');
            }
            $userId = (int)$param['userId'];
            $type = (int)$param['type'];
            $type_id = (int)$param['type_id'];

            $admin = AdminModel::queryFirst(['id'=>$userId],['group_id']);
            if(empty($admin)){
                return ToolUtil::returnJson(301,'用户不存在');
            }

            if($admin['group_id'] !== 1){
                return ToolUtil::returnJson(303,'不是超级管理员');
            }

            if(!ToolUtil::checkExcelSuffix($param)){
                return ToolUtil::returnJson(302,'文件类型必须为xlsx或xls');
            }
            $phpReader = new \PHPExcel_Reader_Excel2007();
            $phpExcel = $phpReader->load($param['file']);
            $currentSheet = $phpExcel->getSheet(0);//获取第一个表单
            $allRow = $currentSheet->getHighestRow();//获取总行数
            $maxColumn = $currentSheet->getHighestColumn();//获取最大列号
            $allColumn=\PHPExcel_Cell::columnIndexFromString($maxColumn);//获取总列数

            if($allRow > 1001){
                return ToolUtil::returnJson(302,'不能超过1000条');
            }
            if($allColumn !== 1){
                return ToolUtil::returnJson(302,'格式不对');
            }

            $snLenArr = [];//记录不等于12位的sn码行数
            $success = 0;//记录成功数
            $errorAll = [];//记录失败行数
            $existenceArr = [];//存在sn行数
            $createTime = time();
            $param['remark'] = '导入sn码';

            DB::beginTransaction();
            set_time_limit(0);
            for ($currentRow=2;$currentRow<=$allRow;$currentRow++){
                for ($currentColumn=0;$currentColumn<$allColumn;$currentColumn++){
                    $val = trim($currentSheet->getCellByColumnAndRow($currentColumn,$currentRow)->getValue());
                    if(strlen($val)!==12){
                        $snLenArr[$currentRow] = $currentRow;
                        break;
                    }
                    $value = AdminSnModel::valueGetId(['value'=>$val]);
                    if($value){
                        $existenceArr[$currentRow] = $currentRow;
                        break;
                    }
                    if(substr($val,1,1)=='N'){
                        $platform = 'MTK';
                    }elseif(substr($val,1,1)=='R'){
                        $platform = '展锐';
                    }else{
                        $platform = '其他';
                    }
                    $sid = AdminSnModel::insertGetId(['value'=>$val,'create_time'=>$createTime,'type'=>$type,'type_id'=>$type_id,'platform'=>$platform]);
                    if($sid){
                        $success++;
                        $param['details'] = ToolUtil::handleSuccessOrError(['sn'=>$val]);
                        LogUtil::addAdminLog($param);
                        break;
                    }else{
                        $errorAll[$currentRow] = $currentRow;
                    }
                }
            }
            DB::commit();
            $result['success'] = $success;
            $result['total'] = $allRow-1;
            $result['snLen'] = array_values($snLenArr);
            $result['errorRow'] = array_values($errorAll);
            $result['existence'] = array_values($existenceArr);
            return ToolUtil::returnJson(200,'成功',$result);
        }catch (\Exception $exception){
            return ToolUtil::returnJson(500,'格式错误');
        }
    }

    /**
     * 增加sn码信息
     * @param $param
     * @return false|string
     */
    public static function addAdminSn($param){

        $uid = (int)$param['userId'];
        $sn = ToolUtil::filterStr($param['snValue']);

        $value = AdminSnModel::valueGetId(['value'=>$sn]);
        if($value){
            return ToolUtil::returnJson(301,'存在该sn码');
        }

        $admin = AdminModel::queryFirst(['id'=>$uid],['group_id']);
        if(empty($admin)){
            return ToolUtil::returnJson(302,'用户不存在');
        }

        if($admin['group_id'] !== 1){
            return ToolUtil::returnJson(303,'不是超级管理员');
        }

        $type = (int)$param['type'];
        $type_id = (int)$param['type_id'];

        try {
            DB::beginTransaction();
            $time = time();
            $sid = AdminSnModel::insertGetId(['value'=>$sn,'type'=>$type,'type_id'=>$type_id,'create_time'=>$time]);
            if($sid){

                $param['remark'] = '增加sn信息';
                $param['details'] = ToolUtil::handleSuccessOrError(['sn'=>$sn]);
                LogUtil::addAdminLog($param);

                DB::commit();
                return ToolUtil::returnJson(200,'成功');
            }
            
            DB::rollBack();
            return ToolUtil::returnJson(300,'失败');

        }catch (\Exception $e){
            DB::rollBack();
            return ToolUtil::returnJson(500,'网络拥堵，稍后再试');
        }

    }

    /**
     * 获取sn数据信息
     * @param $param
     * @return false|string
     */
    public static function queryAdminSn($param){
        $admin = AdminModel::queryFirst(['id'=>$param['userId']],['group_id']);
        if($admin['group_id']==1 || $admin['group_id']==2){
            switch ($param['type']){
                case 1:
                    $data = self::handleQueryAdminSn([],$param);
                    break;
                case 2:
                    $param['field'] = 'as.value';
                    $param['as.value'] = $param['snValue'];
                    $data = self::handleQueryAdminSn([],$param);
                    break;
                case 3:
                    $param['field'] = 'as.name';
                    $param['as.name'] = $param['name'];
                    $data = self::handleQueryAdminSn([],$param);
                    break;
                case 4:
                    $param['field'] = 'as.online';
                    $param['as.online'] = $param['online'];
                    $data = self::handleQueryAdminSn([],$param);
                    break;
                default:
                    $data = self::handleQueryAdminSn([],$param);
                    break;
            }
        }elseif($admin['group_id']==3){
            $where=['ts.admin_id'=>$param['userId'],'bsn.status'=>1];
            switch ($param['type']){
                case 1:
                    $data = self::handleQueryAdminSn($where,$param);
                    break;
                case 2:
                    $param['field'] = 'as.value';
                    $param['as.value'] = $param['snValue'];
                    $data = self::handleQueryAdminSn($where,$param);
                    break;
                case 3:
                    $param['field'] = 'as.name';
                    $param['as.name'] = $param['name'];
                    $data = self::handleQueryAdminSn($where,$param);
                    break;
                case 4:
                    $param['field'] = 'as.online';
                    $param['as.online'] = $param['online'];
                    $data = self::handleQueryAdminSn($where,$param);
                    break;
                default:
                    $data = self::handleQueryAdminSn($where,$param);
                    break;
            }
        }else{
            $where=['ps.admin_id'=>$param['userId'],'bsn.status'=>1];
            switch ($param['type']){
                case 1:
                    $data = self::handleQueryAdminSn($where,$param);
                    break;
                case 2:
                    $param['field'] = 'as.value';
                    $param['as.value'] = $param['snValue'];
                    $data = self::handleQueryAdminSn($where,$param);
                    break;
                case 3:
                    $param['field'] = 'as.name';
                    $param['as.name'] = $param['name'];
                    $data = self::handleQueryAdminSn($where,$param);
                    break;
                case 4:
                case 5:
                    $param['field'] = 'as.online';
                    $param['as.online'] = $param['online'];
                    $data = self::handleQueryAdminSn($where,$param);
                    break;
                default:
                    $data = self::handleQueryAdminSn($where,$param);
                    break;
            }
        }
        if(count($data['data'])){

            foreach ($data['data'] as $key => $value) {
                $data['data'][$key]['card_info'] = json_decode($data['data'][$key]['card_info'],true);
            }

            return ToolUtil::returnJson(200,'成功',$data['data'],$data['count']);
        }else{
            return ToolUtil::returnJson(400,'没有数据');
        }
    }

    /**
     * 处理获取的sn信息
     * @param array $where
     * @param $param
     * @return \Illuminate\Support\Collection
     */
    public static function handleQueryAdminSn($where=[],$param){
        if($where){
            $count = AdminSnModel::queryCount($where,$param);
            $page = ToolUtil::calculationPage($param,$count);
            $data['data'] = AdminSnModel::queryAll($where,$param,$page);
            $data['count'] = $count;
        }else{
            $count = AdminSnModel::queryCount([],$param);
            $page = ToolUtil::calculationPage($param,$count);
            $data['data'] = AdminSnModel::queryAll([],$param,$page);
            $data['count'] = $count;
        }
        return $data;
    }

    /**
     * 删除sn信息
     * @param $param
     * @return false|string
     */
    public static function deleteAdminSn($param){

        try{
            $admin = AdminModel::queryFirst(['id'=>$param['userId']],['group_id','sn_num']);
            if(!empty($admin)){

                DB::beginTransaction();
                if($admin['group_id'] !== 1){
                    return ToolUtil::returnJson(303,'不是超级管理员');
                }

                $where = ['admin_sn_id'=>$param['id']];
                
                $adminSn = AdminSnModel::queryWhereFirst(['a.id'=>$param['id']]);
                $adminCount = AdminSnModel::delete(['id'=>$param['id']]);
                $int = 0;

                $new_sn_num_flag = true;
                $t_parent_sn = DB::table('t_parent_sn')->where($where)->first(['admin_id']);
                if(!empty($t_parent_sn['admin_id'])){
                    $t_admin = DB::table('t_admin')->where(['id'=>$t_parent_sn['admin_id']])->first(['sn_num']);
                    $new_sn_num = $t_admin['sn_num'] - 1;
                    if($new_sn_num > 0){
                        $new_sn_num = 0;
                    }
                    $new_sn_num_flag = DB::table('t_admin')->where(['id'=>$t_parent_sn['admin_id']])->update(['sn_num'=>$new_sn_num]);
                }

                if($adminSn && $adminCount>0 && $new_sn_num_flag){

                    $int = 1;
                    $parentCount = ParentSnModel::delete($where);
                    if($parentCount>0){
                        $int = 2;
                    }

                    $teacherCount = TeacherSnModel::delete($where);
                    $batchCount = BatchModel::delete(['id'=>$adminSn['id']]);
                    if($teacherCount>0 && $batchCount>0){
                        $int = 2;
                    }

                    AppInstallModel::delete(['sn_value'=>$adminSn['value']]);
                    DB::table('t_sn_uid')->where(['sn'=>$adminSn['value']])->delete();
                    DB::table('t_app_jump')->where(['sn'=>$adminSn['value']])->delete();
                    DB::table('t_app_log')->where(['sn_value'=>$adminSn['value']])->delete();
                    DB::table('t_app_test')->where(['sn'=>$adminSn['value']])->delete();
                    DB::table('t_bind_sn')->where(['sn_value'=>$adminSn['value']])->delete();
                    DB::table('t_browser')->where(['sn_value'=>$adminSn['value']])->delete();
                    DB::table('t_screenshot')->where(['sn_value'=>$adminSn['value']])->delete();
                    DB::table('t_send_teacher')->where(['sn_value'=>$adminSn['value']])->delete();
                    DB::table('t_setting')->where(['sn_value'=>$adminSn['value']])->delete();
                    DB::table('t_time_control')->where(['sn_value'=>$adminSn['value']])->delete();
                    DB::table('t_app_use_info')->where(['sn'=>$adminSn['value']])->delete();

                }

                $param['remark'] = '删除sn信息';
                if($int==2){
                    $param['status'] = 1;
                    $param['contentType'] = 17;
                    $param['type'] = 2;
                    $param['statusType'] = '删除sn信息';
                    $param['batch'] = array($adminSn['value']);
                    $param['details'] = ToolUtil::handleSuccessOrError(['sn'=>$adminSn['value']]);
                    LogUtil::addAdminLog($param);
                    $jPush = LogUtil::addPushLog($param);
                    if(in_array(200,$jPush)){
                        DB::commit();
                        return ToolUtil::returnJson(200,'成功,推送成功');
                    }else{
                        DB::commit();
                        return ToolUtil::returnJson(200,'成功,推送失败');
                    }
                }elseif($int==1){
                    DB::commit();
                    $param['details'] = ToolUtil::handleSuccessOrError(['sn'=>$adminSn['value']]);
                    LogUtil::addAdminLog($param);
                    return ToolUtil::returnJson(200,'成功');
                }else{
                    DB::rollBack();
                    return ToolUtil::returnJson(300,'失败');
                }
            }else{
                return ToolUtil::returnJson(301,'不存在该用户');
            }

        }catch (\Exception $e){
            DB::rollBack();
            return ToolUtil::returnJson(500,$e->getMessage());
        }

    }

    /**
     * 解除sn授权信息
     * @param $param
     * @return false|string
     */
    public static function onEmpower($param){
        return ToolUtil::returnJson(300,'弃用');
        $admin = AdminModel::queryFirst(['id'=>$param['userId']],['group_id']);
        if($admin['group_id']==1 || $admin['group_id']==2){
            return ToolUtil::returnJson(301,'没有权限');
        }
        DB::beginTransaction();
        $pCount = ParentSnModel::edit(['admin_sn_id'=>$param['id']],['teacher_id'=>null]);
        $tCount = TeacherSnModel::delete(['admin_sn_id'=>$param['id']]);
        $param['remark'] = '解除授权';
        $adminSn = AdminSnModel::queryFirst(['id'=>$param['id']],['value']);
        if($pCount>0 && $tCount>0){
            $param['details'] = ToolUtil::handleSuccessOrError(['sn'=>$adminSn['value']]);
            LogUtil::addAdminLog($param);
            AppInstallModel::delete(['sn_value'=>$adminSn['value']]);
            SendTeacherModel::delete(['sn_value'=>$adminSn['value']]);
            DB::commit();
            $param['status'] = 1;
            $param['contentType'] = 17;
            $param['type'] = 2;
            $param['statusType'] = '解除授权绑定';
            $param['batch'] = array($adminSn['value']);
            $jPush = LogUtil::addPushLog($param);
            if(in_array(200,$jPush)){
                return ToolUtil::returnJson(200,'成功');
            }
            return ToolUtil::returnJson(200,'成功,推送失败');
        }
        DB::rollBack();
        $param['details'] = ToolUtil::handleSuccessOrError(['sn'=>$adminSn['value']],0);
        LogUtil::addAdminLog($param);
        return ToolUtil::returnJson(300,'失败');
    }

    /**
     * 解除绑定的sn信息
     * @param $param
     * @return false|string
     */
    public static function onBindSn($param){
        $admin = AdminModel::queryFirst(['id'=>$param['userId']],['group_id']);
        if($admin['group_id']==4){
            $parent = ParentSnModel::queryFirst(['admin_sn_id'=>$param['id']],['teacher_id']);
            $adminSn = AdminSnModel::queryFirst(['id'=>$param['id']],['value']);
            DB::beginTransaction();
            $param['remark'] = '解除绑定sn';
            $param['status'] = 1;
            $param['contentType'] = 17;
            $param['type'] = 2;
            $param['statusType'] = '解除绑定sn';
            $param['batch'] = array($adminSn['value']);
            if($parent['teacher_id']){
                $tCount = TeacherSnModel::delete(['admin_sn_id'=>$param['id']]);
                if($tCount>!0){
                    $param['details'] = ToolUtil::handleSuccessOrError(['sn'=>$adminSn['value']],0);
                    LogUtil::addAdminLog($param);
                    DB::rollBack();
                    return ToolUtil::returnJson(300,'失败');
                }
            }
            $pCount = ParentSnModel::delete(['admin_sn_id'=>$param['id']]);
            AppInstallModel::delete(['sn_value'=>$adminSn['value']]);
            $tCount = TeacherSnModel::delete(['sn_value'=>$adminSn['value']]);
            if($pCount>!0 || $tCount>!0){
                DB::rollBack();
                $param['details'] = ToolUtil::handleSuccessOrError(['sn'=>$adminSn['value']],0);
                LogUtil::addAdminLog($param);
                return ToolUtil::returnJson(300,'失败');
            }
            $jPush = LogUtil::addPushLog($param);
            $param['details'] = ToolUtil::handleSuccessOrError(['sn'=>$adminSn['value']]);
            LogUtil::addAdminLog($param);
            DB::commit();
            if(in_array(200,$jPush)){
                return ToolUtil::returnJson(200,'成功');
            }
            return ToolUtil::returnJson(200,'成功,推送失败');
        }
        return ToolUtil::returnJson(301,'没有权限');
    }

    /**
     * 更换班级信息
     * @param $param
     * @return false|string
     * @throws \PHPExcel_Exception
     * @throws \PHPExcel_Reader_Exception
     */
    public static function importUpdateSn($param){
        return ToolUtil::returnJson(302,'已弃用');
        if(!ToolUtil::checkExcelSuffix($param)){
            return ToolUtil::returnJson(302,'文件类型必须为xlsx或xls');
        }
        $phpReader = new \PHPExcel_Reader_Excel2007();
        $phpExcel = $phpReader->load($param['file']);
        $currentSheet = $phpExcel->getSheet(0);//获取第一个表单
        $allRow = $currentSheet->getHighestRow();//获取总行数
        $maxColumn = $currentSheet->getHighestColumn();//获取最大列号
        $allColumn=\PHPExcel_Cell::columnIndexFromString($maxColumn);//获取总列数
        $snLenArr = [];
        $noSn = [];
        $errorArr = [];
        $success = 0;
        $param['remark'] = '更换班级';
        $sn = [];
        DB::beginTransaction();
        for ($currentRow=2;$currentRow<=$allRow;$currentRow++){
            for ($currentColumn=0;$currentColumn<$allColumn;$currentColumn++) {
                $val = trim($currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue());
                if(strlen($val)!==12){
                    $param['details'] = ToolUtil::handleSuccessOrError(['sn'=>$val,'remark'=>'大于或小于12'],0);
                    LogUtil::addAdminLog($param);
                    $snLenArr[$currentRow]=$currentRow;
                    break;
                }
                $teacher = TeacherSnModel::queryWhereFirst(['a.value'=>$val]);
                if(!$teacher){
                    $param['details'] = ToolUtil::handleSuccessOrError(['sn'=>$val,'remark'=>'不存在该sn码'],0);
                    LogUtil::addAdminLog($param);
                    $noSn[$currentRow] = $currentRow;
                    break;
                }
                $batch = BatchModel::queryFirst(['name'=>$param['name']],['id','rand_code']);
                $tCount = TeacherSnModel::edit(['id'=>$teacher['id']],['batch_id'=>$batch['id']]);
                $sCount = SendTeacherModel::edit(['sn_value'=>$val],['batch_rand'=>$batch['rand_code']]);
                AppInstallModel::delete(['sn_value'=>$val]);
                if($tCount>!0 || $sCount>!0){
                    $param['details'] = ToolUtil::handleSuccessOrError(['sn'=>$val,'remark'=>'操作失败'],0);
                    LogUtil::addAdminLog($param);
                    $errorArr[$currentRow] = $currentRow;
                    break;
                }
                $success++;
                $sn[$currentRow] = $val;
                $param['details'] = ToolUtil::handleSuccessOrError(['sn'=>$val]);
                LogUtil::addAdminLog($param);
            }
        }
        $result['snLen'] = array_values($snLenArr);
        $result['noSn'] = array_values($noSn);
        $result['error'] = array_values($errorArr);
        $result['success'] = $success;
        $result['total'] = $allRow-1;
        $param['status'] = 1;
        $param['contentType'] = 17;
        $param['type'] = 2;
        $param['statusType'] = '更换班级';
        if($sn){
            DB::commit();
            $param['batch'] = $sn;
            $jPush = LogUtil::addPushLog($param);
            if(in_array(200,$jPush)){
                return ToolUtil::returnJson(200,'成功',$result);
            }else{
                return ToolUtil::returnJson(200,'成功',$result);
            }
        }
        return ToolUtil::returnJson(200,'成功',$result);
    }

    /**
     * 获取班级信息
     * @param $param
     * @return false|string
     */
    public static function queryBatch($param){
        $admin = AdminModel::queryFirst(['id'=>$param['userId']],['group_id']);
        if($admin['group_id']==1 || $admin['group_id']==2){
            switch ($param['type']){
                case 1:
                    $data = self::handleQueryBatch([],$param);
                    break;
                case 2:
                    if(!isset($param['name'])){
                        return ToolUtil::returnJson(401,'班级名称为空或不存在该参数');
                    }
                    $param['field'] = 'b.name';
                    $param['b.name'] = $param['name'];
                    $data = self::handleQueryBatch([],$param);
                    break;
                case 3:
                    if(!isset($param['randCode'])){
                        return ToolUtil::returnJson(401,'邀请码为空或不存在该参数');
                    }
                    $param['field'] = 'b.rand_code';
                    $param['b.rand_code'] = $param['randCode'];
                    $data = self::handleQueryBatch([],$param);
                    break;
                default:
                    $data = self::handleQueryBatch([],$param);//
                    break;
            }
        }else{
            $where['b.admin_id'] = $param['userId'];
            switch ($param['type']){
                case 1:
                    $data = self::handleQueryBatch($where,$param);
                    break;
                case 2:
                    if(!isset($param['name'])){
                        return ToolUtil::returnJson(401,'班级名称为空或不存在该参数');
                    }
                    $param['field'] = 'b.name';
                    $param['b.name'] = $param['name'];
                    $data = self::handleQueryBatch($where,$param);
                    break;
                case 3:
                    if(!isset($param['randCode'])){
                        return ToolUtil::returnJson(401,'邀请码为空或不存在该参数');
                    }
                    $param['field'] = 'b.rand_code';
                    $param['b.rand_code'] = $param['randCode'];
                    $data = self::handleQueryBatch($where,$param);
                    break;
                default:
                    $data = self::handleQueryBatch($where,$param);//
                    break;
            }
        }
        if(count($data['data'])){
            return ToolUtil::returnJson(200,'成功',$data['data'],$data['count']);
        }
        return ToolUtil::returnJson(400,'没有数据');
    }

    /**
     * 处理获取班级信息
     * @param array $where
     * @param $param
     * @return mixed
     */
    public static function handleQueryBatch($where=[],$param){
        if($where){
            $count = BatchModel::queryCount($where,$param);
            $page = ToolUtil::calculationPage($param,$count);
            $data['data'] = BatchModel::queryAll($where,$param,$page);
            $data['count'] = $count;
        }else{
            $count = BatchModel::queryCount([],$param);
            $page = ToolUtil::calculationPage($param,$count);
            $data['data'] = BatchModel::queryAll([],$param,$page);
            $data['count'] = $count;
        }
        return $data;
    }

    /**
     * 编号获取班级信息
     * @param $param
     * @return false|string
     */
    public static function queryIdBatch($param){
        $data = BatchModel::queryFirst(['id'=>$param['id']],['id','name']);
        if($data){
            return ToolUtil::returnJson(200,'成功',$data);
        }
        return ToolUtil::returnJson(400,'没有数据');
    }

    /**
     * 增加班级信息
     * @param $param
     * @return false|string
     */
    public static function addBatch($param){
        $batch = BatchModel::queryFirst(['name'=>$param['name'],'admin_id'=>$param['userId']],['id']);
        if($batch){
            return ToolUtil::returnJson(301,'存在相同班级名称');
        }
        $param['remark'] = '添加班级信息';
        $randCode = substr(time(),-6).$param['userId'];
        $int = BatchModel::add(['name'=>$param['name'],'admin_id'=>$param['userId'],'rand_code'=>$randCode,'create_time'=>time()]);
        if($int){
            $param['details'] = ToolUtil::handleSuccessOrError(['className'=>$param['name']]);
            LogUtil::addAdminLog($param);
            return ToolUtil::returnJson(200,'成功');
        }
        return ToolUtil::returnJson(300,'失败');
    }

    /**
     * 编辑班级信息
     * @param $param
     * @return false|string
     */
    public static function editBatch($param){
        $batch = BatchModel::queryFirst(['name'=>$param['name'],'admin_id'=>$param['userId']],['id']);
        $param['remark'] = '编辑班级信息';
        if(!empty($batch) && $batch['id']!=$param['id']){
            return ToolUtil::returnJson(301,'存在相同班级名称');
        }
        $int = BatchModel::edit(['id'=>$param['id']],['name'=>$param['name'],'update_time'=>time()]);
        if($int){
            $param['details'] = ToolUtil::handleSuccessOrError(['className'=>$param['name']]);
            LogUtil::addAdminLog($param);
            return ToolUtil::returnJson(200,'成功');
        }
        return ToolUtil::returnJson(300,'失败');
    }

    /**
     * 删除班级信息
     * @param $param
     * @return false|string
     */
    public static function deleteBatch($param){
        $batch = BatchModel::queryFirst(['id'=>$param['id']],['rand_code','name']);
        if(!$batch){
            return ToolUtil::returnJson(301,'不存在该班级信息');
        }
        $param['remark'] = '删除班级信息';

        try {
            DB::beginTransaction();
            $teacher = TeacherSnModel::queryLeftAdminSnAndBatch(['b.id'=>$param['id']],['a.id','a.value']);
            if(count($teacher)){
                foreach ($teacher as $value){
                    ParentSnModel::edit(['admin_sn_id'=>$value['id']],['teacher_id'=>null]);
                    AppInstallModel::delete(['sn_value'=>$value['value']]);
                    SendTeacherModel::delete(['sn_value'=>$param['id']]);
                }
            }
            $bCount = BatchModel::delete(['id'=>$param['id']]);
            if(!$bCount){
                DB::rollBack();
                return ToolUtil::returnJson(300,'失败');
            }
            $param['batch'] = array($param['id']);
            $param['status'] = 1;
            $param['contentType'] = 17;
            $param['type'] = 1;
            $param['statusType'] = '删除班级信息';
            $param['title'] = 'OK';
            $param['details'] = ToolUtil::handleSuccessOrError(['className'=>$batch['name']]);
            LogUtil::addAdminLog($param);
            $jPush = LogUtil::addPushLog($param);
            DB::commit();
            if(in_array(200,$jPush)){
                return ToolUtil::returnJson(200,'成功');
            }
            return ToolUtil::returnJson(200,'成功,推送失败');

        }catch (\Exception $exception){
            DB::rollBack();
            return ToolUtil::returnJson(500,'网络拥堵，请稍后再试',$exception->getMessage());
        }
    }

    /**
     * sn获取设备硬件信息
     * @param $param
     * @return false|string
     */
    public static function querySnHardware($param){
        $field = ['id','value as sn','model','imel','system','devices_version','orm_version','screen_px','quantity',
            'device_memory','storage','cpu','addr','online','off_line_time'];
        $data = AdminSnModel::queryFirst(['value'=>$param['sn']],$field);
        $app = [];
        if($data){
            $parent = ParentSnModel::queryFirst(['admin_sn_id'=>$data['id']],['create_time']);
            if($parent){
                $data['create_time'] = $parent['create_time'];
            }
            $appInstall = AppInstallModel::queryWhereGet(['sn_value'=>$param['sn']],['id','parent_app_id','teacher_app_id','sys_app_id']);
            if($appInstall){
                $pField = ['a.id','p.app_name','p.app_package','p.app_img','a.app_version_code','p.app_size','a.status','a.lastUpdateTime as create_time'];
                $tField = ['a.id','t.app_name','t.app_package','t.app_img','a.app_version_code','t.app_size','a.status','a.lastUpdateTime as create_time'];
                
                $type = 0;
                foreach ($appInstall as $k=>$v){
                    if($v['parent_app_id']){
                        $type = 3;
                        $app[$k] = AppInstallModel::queryLikeParent(['p.id'=>$v['parent_app_id'],'a.sn_value'=>$param['sn']],$pField);
                    }elseif($v['teacher_app_id']){
                        $type = 2;
                        $app[$k] = AppInstallModel::queryLikeTeacher(['t.id'=>$v['teacher_app_id'],'a.sn_value'=>$param['sn']],$tField);
                    }
                }

                if($type !== 0){
                    $runApp = DB::table('t_run_app')->where(['sn_value'=>$param['sn'],'type'=>$type])->first(['id','app_id']);
                    foreach ($app as $key => $value) {
                        if(!empty($runApp) && $value['id'] === $runApp['app_id']){
                            $app[$key]['status'] = 1;
                        }
                    }
                }

                $data['app'] = array_values(array_filter($app));
                return ToolUtil::returnJson(200,'成功',$data);
            }
            return ToolUtil::returnJson(400,'没有数据');
        }
        return ToolUtil::returnJson(400,'没有数据');
    }


    /**
     * 设备信息刷新
     * @param $param
     * @return false|string
     */
    public static function renovate($param){
        $param['status'] = 1;
        $param['contentType'] = 2;
        $param['type'] = 2;
        $param['statusType'] = '刷新';
        $param['title'] = 'OK';
        $param['batch'] = array($param['sn']);
        $jPush = LogUtil::addPushLog($param);
        if(in_array(200,$jPush)){
            return ToolUtil::returnJson(200,'成功');
        }
        return ToolUtil::returnJson(200,'成功,推送失败');
    }

    /**
     * 单个设备重启或恢复出厂设置
     * @param $param
     * @return false|string
     */
    public static function singleDeviceRestartOrRecovery($param){
        $group_id = DB::table('t_admin')->where('id',$param['userId'])->value('group_id');
        if($group_id==1){
            $sn = DB::table('t_admin_sn')
                ->where('value',$param['sn'])->value('id');
        }elseif($group_id==3){
            $sn = DB::table('t_parent_sn as p')
                ->leftJoin('t_admin_sn as a','p.admin_sn_id','=','a.id')
                ->where(['a.value'=>$param['sn'],'p.teacher_id'=>$param['userId']])->value('p.id');
        }else{
            $sn = DB::table('t_parent_sn as p')
                ->leftJoin('t_admin_sn as a','p.admin_sn_id','=','a.id')
                ->where(['a.value'=>$param['sn'],'p.admin_id'=>$param['userId']])->value('p.id');
        }
        if(empty($sn)){
            return ToolUtil::returnJson(301,'不存在该设备');
        }
        $param['status'] = 1;
        $param['title'] = 'OK';
        $param['batch'] = array($param['sn']);
        if($param['type']==1){
            $param['remark'] = '设备重启';
            $param['statusType'] = '设备重启';
            $param['contentType'] = 22;
        }else{
            $param['remark'] = '设备恢复出厂模式';
            $param['statusType'] = '设备恢复出厂模式';
            $param['contentType'] = 17;
        }
        $param['type'] = 2;
        $param['details'] = ToolUtil::handleSuccessOrError(['sn'=>$param['sn']]);
        LogUtil::addAdminLog($param);
        $jPush = LogUtil::addPushLog($param);
        if(in_array(200,$jPush)){
            return ToolUtil::returnJson(200,'成功');
        }
        return ToolUtil::returnJson(300,'成功，但推送失败，详情请查看推送日志');
    }


    /**
     * 清除安装应用缓存
     * @param $param 安装应用id
     * @return false|string
     */
    public static function cleanInstallAppCache($param){

        $id = (int)$param['id'];

        $appInstall = AppInstallModel::queryFirst(['id'=>$id],['sn_value','parent_app_id','teacher_app_id','sys_app_id']);
        if(!$appInstall){
            return ToolUtil::returnJson(301,'没有安装记录');
        }

        $type = 0;
        if($appInstall['parent_app_id']){
            $type = 4;
            $app = AppInstallModel::queryLikeParent(['p.id'=>$appInstall['parent_app_id'],'a.sn_value'=>$appInstall['sn_value']],['p.app_package','p.admin_id']);
        }else if($appInstall['teacher_app_id']){
            $type = 3;
            $app = AppInstallModel::queryLikeTeacher(['t.id'=>$appInstall['teacher_app_id'],'a.sn_value'=>$appInstall['sn_value']],['t.app_package','t.admin_id']);
        }

        if(empty($app)){
            return ToolUtil::returnJson(302,'没有应用记录');
        }

        $admin_id = $app['admin_id'];
        $app_package = $app['app_package'];

        $param['remark'] = "清除应用缓存";
        $param['userId'] = $admin_id;
        $param['lastIp'] = ToolUtil::get_real_ip();
        $param['status'] = 1;
        $param['contentType'] = 34;
        $param['type'] = 2;
        $param['batch'] = array($appInstall['sn_value']);
        $param['title'] = 'OK';
        $param['statusType'] = '清除应用缓存';
        $jPush = LogUtil::addPushLog($param,['package'=>$app_package]);
        $param['details']=ToolUtil::handleSuccessOrError(['appPackage'=>$app_package,'sn'=>$appInstall['sn_value']]);
        if(in_array(200,$jPush)){
            LogUtil::addAdminLog($param);
            return ToolUtil::returnJson(200,'成功');
        }
        
        return ToolUtil::returnJson(300,'设备不在线或没联网');

    }

    /**
     * 强制停用设备
     * @param $param
     * @return false|string
     */
    public static function forceStopApp($param){

        $id = (int)$param['id'];

        $appInstall = AppInstallModel::queryFirst(['id'=>$id],['sn_value','parent_app_id','teacher_app_id','sys_app_id']);
        if(!$appInstall){
            return ToolUtil::returnJson(301,'没有安装记录');
        }

        $type = 0;
        if($appInstall['parent_app_id']){
            $type = 4;
            $app = AppInstallModel::queryLikeParent(['p.id'=>$appInstall['parent_app_id'],'a.sn_value'=>$appInstall['sn_value']],['p.app_name','p.app_package','p.app_version_code','p.app_size']);
        }else if($appInstall['teacher_app_id']){
            $type = 3;
            $app = AppInstallModel::queryLikeTeacher(['t.id'=>$appInstall['teacher_app_id'],'a.sn_value'=>$appInstall['sn_value']],['t.app_name','t.app_package','t.app_version_code','t.app_size']);
        }

        if(empty($app)){
            return ToolUtil::returnJson(302,'没有应用记录');
        }

        $param['remark'] = '强制停用应用';
        $param['status'] = 1;
        $param['contentType'] = 24;
        $param['type'] = 2;
        $param['statusType'] = '强制停用应用';
        $param['title'] = 'OK';
        $param['batch'] = array($param['sn']);
        $jPush = LogUtil::addPushLog($param,$app);
        if(in_array(200,$jPush)){
            return ToolUtil::returnJson(200,'成功');
        }
        return ToolUtil::returnJson(300,'推送失败，详情请查看推送日志');

    }

    /**
     * 卸载应用
     * @param $param
     * @return false|string
     */
    public static function uninstallApp($param){

        $id = (int)$param['id'];

        $appInstall = AppInstallModel::queryFirst(['id'=>$id],['sn_value','parent_app_id','teacher_app_id','sys_app_id']);
        if(!$appInstall){
            return ToolUtil::returnJson(301,'没有安装记录');
        }

        $type = 0;
        if($appInstall['parent_app_id']){
            $type = 4;
            $app = AppInstallModel::queryLikeParent(['p.id'=>$appInstall['parent_app_id'],'a.sn_value'=>$appInstall['sn_value']],['p.app_name','p.app_package','p.app_version_code','p.app_size']);
        }else if($appInstall['teacher_app_id']){
            $type = 3;
            $app = AppInstallModel::queryLikeTeacher(['t.id'=>$appInstall['teacher_app_id'],'a.sn_value'=>$appInstall['sn_value']],['t.app_name','t.app_package','t.app_version_code','t.app_size']);
        }

        if(empty($app)){
            return ToolUtil::returnJson(302,'没有应用记录');
        }

        $param['remark'] = '卸载应用';
        $param['status'] = 1;
        $param['contentType'] = 10;
        $param['type'] = 2;
        $param['statusType'] = '卸载应用';
        $param['title'] = 'OK';
        $param['batch'] = array($param['sn']);
        $jPush = LogUtil::addPushLog($param,$app);
        if(in_array(200,$jPush)){
            return ToolUtil::returnJson(200,'成功');
        }
        return ToolUtil::returnJson(300,'推送失败，详情请查看推送日志');
            
    }

    /**
     * 设备发起截图
     * @param $param
     * @return false|string
     */
    public static function sendScreenshot($param){
        $parent = ParentSnModel::queryWhereFirst(['a.id'=>$param['id']]);
        if(empty($parent)){
            return ToolUtil::returnJson(301,'设备没绑定');
        }
        $param['status'] = 1;
        $param['type'] = 2;
        $param['batch'] = array($parent['value']);
        $param['title'] = 'OK';
        $param['contentType'] = 26;
        $param['remark'] = '截图';
        $param['statusType'] = '截图';
        $param['details'] = ToolUtil::handleSuccessOrError(['sn'=>$parent['value']]);
        LogUtil::addAdminLog($param);
        $jPush = LogUtil::addPushLog($param);
        if(in_array(200,$jPush)){
            return ToolUtil::returnJson(200,'成功');
        }
        return ToolUtil::returnJson(300,'推送失败，详情请查看推送日志');
    }

    /**
     * 获取截图信息
     * @param $param
     * @return false|string
     */
    public static function queryScreenshot($param){
        $admin = AdminSnModel::queryFirst(['id'=>$param['id']],['value']);
        if(empty($admin)){
            return ToolUtil::returnJson(301,'不存在该设备');
        }
        $data = ScreenshotModel::queryGet(['sn_value'=>$admin['value']],['id','img','create_time']);
        if(count($data)){
            return ToolUtil::returnJson(200,'成功',$data);
        }
        return ToolUtil::returnJson(400,'没有数据');
    }

    /**
     * 清除截图信息
     * @param $param
     * @return false|string
     */
    public static function deleteScreenshot($param){
        $admin = AdminSnModel::queryFirst(['id'=>$param['id']],['value']);
        if(empty($admin)){
            return ToolUtil::returnJson(301,'该设备没有绑定');
        }
        $screen = ScreenshotModel::queryFirst(['sn_value'=>$admin['value']],['id']);
        if(empty($screen)){
            return ToolUtil::returnJson(302,'没有截图信息，不需要清除');
        }
        $param['remark'] = '清除截图';
        $param['details'] = ToolUtil::handleSuccessOrError(['sn'=>$admin['value']]);
        ScreenshotModel::delete(['sn_value'=>$admin['value']]);
        return ToolUtil::returnJson(200,'成功');
    }

    /**
     * 家长增加时间管控
     * @param $param
     * @return false|string
     */
    public static function addParentTimeControl($param){
        $parent = ParentSnModel::queryWhereFirst(['a.id'=>$param['id']]);
        if(empty($parent)){
            return ToolUtil::returnJson(301,'该设备没有绑定');
        }
        if($parent['teacher_id']){
            return ToolUtil::returnJson(302,'该设备已授权给老师');
        }
        $param['remark'] = '增加时间管控';
        $param['details'] = ToolUtil::handleSuccessOrError(['sn'=>$parent['value']]);

        if(isset($param['day_type'])){
            $day_type = $param['day_type'];
        }else{
            $day_type = 0;
        }

        $timeControl = TimeControlModel::queryFirst(['sn_value'=>$parent['value'],'day_type'=>$day_type],['id']);
        if($timeControl){
            return ToolUtil::returnJson(303,'不能重复添加值');
        }
        $data = [
            'start_time'=>$param['startTime'],
            'end_time'=>$param['endTime'],
            'create_time'=>time(),
            'day_type'=>$day_type,
            'sn_value'=>$parent['value'],
            'admin_id'=>$param['userId']
        ];
        if(TimeControlModel::add($data)){
            $param['status'] = 1;
            $param['type'] = 2;
            $param['batch'] = array($parent['value']);
            $param['title'] = 'OK';
            $param['contentType'] = 27;
            $param['remark'] = '增加时间管控';
            $param['statusType'] = '增加时间管控';
            $param['details'] = ToolUtil::handleSuccessOrError(['sn'=>$parent['value']]);
            LogUtil::addAdminLog($param);
            $jPush = LogUtil::addPushLog($param);
            if(in_array(200,$jPush)){
                return ToolUtil::returnJson(200,'成功');
            }
            return ToolUtil::returnJson(200,'成功，但推送失败，详情请查看推送日志');
        }
        return ToolUtil::returnJson(300,'失败');
    }

    /**
     * 老师增加时间管控
     * @param $param
     * @return false|string
     */
    public static function addTeacherTimeControl($param){
        try {

            if(isset($param['day_type'])){
                $day_type = $param['day_type'];
            }else{
                $day_type = 0;
            }

            $batchArr = explode(',',$param['bId']);
            foreach ($batchArr as $v){
                $timeControl = DB::table('t_time_control')->where(['day_type'=>$day_type])->whereRaw(" find_in_set('{$v}',batch_id) ")->first(['id']);
                if($timeControl){
                    return ToolUtil::returnJson(302,'存在相同班级');
                }
            }

            $data = [
                'start_time'=>$param['startTime'],
                'end_time'=>$param['endTime'],
                'create_time'=>time(),
                'day_type'=>$day_type,
                'batch_id'=>$param['bId'],
                'admin_id'=>$param['userId']
            ];
            if(TimeControlModel::add($data)){
                $param['status'] = 1;
                $param['type'] = 1;
                $param['batch'] = $batchArr;
                $param['title'] = 'OK';
                $param['contentType'] = 27;
                $param['remark'] = '增加时间管控';
                $param['statusType'] = '增加时间管控';
                $param['details'] = ToolUtil::handleSuccessOrError(['batch'=>$param['bId']]);
                LogUtil::addAdminLog($param);
                $jPush = LogUtil::addPushLog($param);
                if(in_array(200,$jPush)){
                    return ToolUtil::returnJson(200,'成功');
                }
                return ToolUtil::returnJson(200,'成功，但推送失败，详情请查看推送日志');
            }
            return ToolUtil::returnJson(300,'失败');
        }catch (\Exception $exception){
            return ToolUtil::returnJson(500,'网络拥堵，请稍后再试');
        }
    }

    /**
     * 获取时间管控
     * @param $param
     * @return false|string
     */
    public static function queryTimeControl($param){
        $admin = AdminModel::queryFirst(['id'=>$param['userId']],['group_id']);
        if(empty($admin)){
            return ToolUtil::returnJson(301,'不存在该用户');
        }
        if($param['status']==1){
            if($admin['group_id']==1 || $admin['group_id']==2){
                switch ($param['type']){
                    case 1:
                        $data = self::handleParentTimeControl([],$param);
                        break;
                    case 2:
                        if(!isset($param['sn']) || empty($param['sn'])){
                            return ToolUtil::returnJson(401,'设备码为空');
                        }
                        $param['field'] = 't.sn_value';
                        $param['t.sn_value'] = $param['sn'];
                        $data = self::handleParentTimeControl([],$param);
                        break;
                    case 3:
                        if(!isset($param['username']) || empty($param['username'])){
                            return ToolUtil::returnJson(401,'用户名为空');
                        }
                        $param['field'] = 'a.username';
                        $param['a.username'] = $param['username'];
                        $data = self::handleParentTimeControl([],$param);
                        break;
                    default:
                        return ToolUtil::returnJson(401,'类型参数不对');
                }
            }else{
                $where['t.admin_id'] = $param['userId'];
                switch ($param['type']){
                    case 1:
                        $data = self::handleParentTimeControl($where,$param);
                        break;
                    case 2:
                        if(!isset($param['sn']) || empty($param['sn'])){
                            return ToolUtil::returnJson(401,'设备码为空');
                        }
                        $param['field'] = 't.sn_value';
                        $param['t.sn_value'] = $param['sn'];
                        $data = self::handleParentTimeControl($where,$param);
                        break;
                    case 3:
                        if(!isset($param['username']) || empty($param['username'])){
                            return ToolUtil::returnJson(401,'用户名为空');
                        }
                        $param['field'] = 'a.username';
                        $param['a.username'] = $param['username'];
                        $data = self::handleParentTimeControl($where,$param);
                        break;
                    default:
                        return ToolUtil::returnJson(401,'类型参数不对');
                }
            }

            if(count($data['data'])){
                $result = [];
                foreach ($data['data'] as $k=>$v){
                    $v['snName'] = AdminSnModel::queryFirst(['value'=>$v['sn_value']],['name'])['name'];
                    $result[$k] = $v;
                }
                return ToolUtil::returnJson(200,'成功',$result,$data['count']);
            }
            return ToolUtil::returnJson(400,'没有数据');

        }else{
            if($admin['group_id']==1 || $admin['group_id']==2){
                switch ($param['type']){
                    case 1:
                        $data = self::handleTeacherTimeControl([],$param);
                        break;
                    case 2:
                        $batch = BatchModel::queryFirst(['name'=>$param['name']],['id']);
                        $param['field'] = 't.batch_id';
                        $param['t.batch_id'] = $batch['id'];
                        $data = self::handleTeacherTimeControl([],$param);
                        break;
                    case 3:
                        $param['field'] = 'a.username';
                        $param['a.username'] = $param['username'];
                        $data = self::handleTeacherTimeControl([],$param);
                        break;
                    default:
                        return ToolUtil::returnJson(401,'类型参数不对');
                }
            }else{
                $where['t.admin_id'] = $param['userId'];
                switch ($param['type']){
                    case 1:
                        $data = self::handleTeacherTimeControl($where,$param);
                        break;
                    case 2:
                        $batch = BatchModel::queryFirst(['name'=>$param['name']],['id']);
                        $param['field'] = 't.batch_id';
                        $param['t.batch_id'] = $batch['id'];
                        $data = self::handleTeacherTimeControl($where,$param);
                        break;
                    case 3:
                        $param['field'] = 'a.username';
                        $param['a.username'] = $param['username'];
                        $data = self::handleTeacherTimeControl($where,$param);
                        break;
                    default:
                        return ToolUtil::returnJson(401,'类型参数不对');
                }
            }

            if(!empty($data['data'])){

                return ToolUtil::returnJson(200,'成功',$data['data'],$data['count']);
            }
            return ToolUtil::returnJson(400,'没有数据');

        }

    }

    private static function handleParentTimeControl($where,$param){
        if($where){
            $data['count'] = TimeControlModel::queryParentCount($where,$param);
            $page = ToolUtil::calculationPage($param,$data['count']);
            $data['data'] = TimeControlModel::queryParentAll($where,$param,$page);
        }else{
            $data['count'] = TimeControlModel::queryParentCount([],$param);
            $page = ToolUtil::calculationPage($param,$data['count']);
            $data['data'] = TimeControlModel::queryParentAll([],$param,$page);
        }
        return $data;
    }

    private static function handleTeacherTimeControl($where,$param){
        if($where){
            $data['count'] = TimeControlModel::queryTeacherCount($where,$param);
            $page = ToolUtil::calculationPage($param,$data['count']);
            $data['data'] = TimeControlModel::queryTeacherAll($where,$param,$page);
        }else{
            $data['count'] = TimeControlModel::queryTeacherCount([],$param);
            $page = ToolUtil::calculationPage($param,$data['count']);
            $data['data'] = TimeControlModel::queryTeacherAll([],$param,$page);
        }
        if(count($data['data'])){
            foreach ($data['data'] as $k=>$v){
                $batchArr = explode(',',$v['batch_id']);
                $arr = [];
                foreach ($batchArr as $key=>$value){
                    $arr[$key] = BatchModel::whereField(['id'=>$value],'name');
                }
                $v['batch_id'] = implode(',',$arr);
                $data['data'][$k] = $v;
            }
        }
        return $data;
    }

    /**
     * 编号获取时间管控
     * @param $param
     * @return false|string
     */
    public static function queryIdTimeControl($param){
        if($param['status']==1){
            $field = ['t.id','a.username','t.start_time','t.end_time','t.sn_value','t.create_time','t.day_type'];
            $data = TimeControlModel::queryLeftFirst(['t.id'=>$param['id']],$field);
        }else{
            $field = ['t.id','a.username','t.start_time','t.end_time','t.batch_id','t.create_time','t.day_type'];
            $data = TimeControlModel::queryLeftFirst(['t.id'=>$param['id']],$field);
        }
        if($data){
            return ToolUtil::returnJson(200,'成功',$data);
        }
        return ToolUtil::returnJson(400,'没有数据');
    }

    /**
     * 修改时间管控
     * @param $param
     * @return false|string
     */
    public static function updateTimeControl($param){
        $timeControl = TimeControlModel::queryFirst(['id'=>$param['id']],['sn_value','batch_id']);
        if(empty($timeControl)){
            return ToolUtil::returnJson(301,'该信息不存在');
        }
        if($param['status']==1){
            $parent = ParentSnModel::queryWhereFirst(['a.value'=>$timeControl['sn_value']]);
            if(empty($parent)){
                return ToolUtil::returnJson(302,'该设备没有绑定');
            }
            if($parent['teacher_id']){
                return ToolUtil::returnJson(303,'该设备授权给老师');
            }
            $data = [
                'start_time'=>$param['startTime'],
                'end_time'=>$param['endTime'],
                'update_time'=>time()
            ];
            $param['batch'] = array($timeControl['sn_value']);
            $param['type'] = 2;
            $param['details'] = ToolUtil::handleSuccessOrError(['sn'=>$timeControl['sn_value']]);
        }else{
            $data = [
                'start_time'=>$param['startTime'],
                'end_time'=>$param['endTime'],
                'update_time'=>time()
            ];
            $param['batch'] = explode(',',$timeControl['batch_id']);
            $param['type'] = 1;
            $param['details'] = ToolUtil::handleSuccessOrError(['batch'=>'编号为:'.$timeControl['batch_id']]);
        }
        if(TimeControlModel::edit(['id'=>$param['id']],$data)){
            $param['contentType'] = 27;
            $param['remark'] = '编辑时间管控';
            $param['statusType'] = '编辑时间管控';
            LogUtil::addAdminLog($param);
            $jPush = LogUtil::addPushLog($param);
            if(in_array(200,$jPush)){
                return ToolUtil::returnJson(200,'成功');
            }
            return ToolUtil::returnJson(200,'成功，但推送失败，详情请查看推送日志');
        }
        return ToolUtil::returnJson(300,'失败');
    }

    /**
     * 删除时间管控
     * @param $param
     * @return false|string
     */
    public static function deleteTimeControl($param){
        $timeControl = TimeControlModel::queryFirst(['id'=>$param['id']],['sn_value','batch_id']);
        if(empty($timeControl)){
            return ToolUtil::returnJson(301,'该信息不存在');
        }
        if($param['status']==1){
            $param['batch'] = array($timeControl['sn_value']);
            $param['type'] = 2;
            $param['details'] = ToolUtil::handleSuccessOrError(['sn'=>$timeControl['sn_value']]);
            $parent = ParentSnModel::queryWhereFirst(['a.value'=>$timeControl['sn_value']]);
            if(empty($parent)){
                return ToolUtil::returnJson(302,'该设备没有绑定');
            }
            if($parent['teacher_id']){
                return ToolUtil::returnJson(303,'该设备授权给老师');
            }
        }else{
            $param['batch'] = explode(',',$timeControl['batch_id']);
            $param['type'] = 1;
            $param['details'] = ToolUtil::handleSuccessOrError(['batch'=>'编号为:'.$timeControl['batch_id']]);
        }
        if(TimeControlModel::delete(['id'=>$param['id']])){
            $param['status'] = 1;//推送的状态用1
            $param['contentType'] = 27;
            $param['remark'] = '删除时间管控';
            $param['statusType'] = '删除时间管控';
            LogUtil::addAdminLog($param);
            $jPush = LogUtil::addPushLog($param);
            if(in_array(200,$jPush)){
                return ToolUtil::returnJson(200,'删除成功');
            }
            return ToolUtil::returnJson(200,'删除成功，但推送失败，详情请查看推送日志');
        }
        return ToolUtil::returnJson(300,'失败');
    }
}